// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * This is an example of writing an Apps Script which uses a service account to
 * access the chromeperf API.
 *
 * Steps to get this working:
 * 1. If you don't already have a service account, create one
 *    and store the generated JSON file in Google Drive. See
 *    https://developers.google.com/identity/protocols/OAuth2ServiceAccount#creatinganaccount
 *    Note the file id in the url (should look like '0Bxxx...') and
 *    replace DRIVE_FILE_ID variable with it.
 * 2. Ask a chromeperf admin to add the account to project-chromeperf-api-access
 *    group on chrome-infra-auth.
 * 3. Create an apps script at script.google.com and paste this file in.
 * 4. Add the apps-script-oauth2 library for authentication
 *    (https://github.com/googlesamples/apps-script-oauth2):
 *    Resources>Libraries>paste in this key and pick most recent version:
 *    1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF
 * 5. Update the code that posts to chromeperf.appspot.com below with the
 *    API calls you need.
 */

// This must be filled in. This is the ID of the file in Google Drive
// where the private key json generated by the API console for your
// service account is stored.
const DRIVE_FILE_ID = '0B...';

function run() {
  const service = getService(getPrivateKeyDetailsFromDriveFile(DRIVE_FILE_ID));
  if (service.hasAccess()) {
    // Make API calls by adding the Authorization header.
    const url = 'https://chromeperf.appspot.com/api/alerts/bug_id/713717';
    const response = UrlFetchApp.fetch(url, {
      method: 'POST',
      headers: {
        Authorization: 'Bearer ' + service.getAccessToken()
      }
    });
    const result = JSON.parse(response.getContentText());
    Logger.log(JSON.stringify(result, null, 2));
  } else {
    Logger.log(service.getLastError());
  }
}

/**
 * Configures the service.
 * @param {Object} privateKeyDetails Dict with private key and client email.
 */
function getService(privateKeyDetails) {
  return OAuth2.createService('PerfDash:' + Session.getActiveUser().getEmail())
      // Set the endpoint URL.
      .setTokenUrl('https://accounts.google.com/o/oauth2/token')

      // Set the private key and issuer.
      .setPrivateKey(privateKeyDetails.private_key)
      .setIssuer(privateKeyDetails.client_email)

      // Set the property store where authorized tokens should be persisted.
      .setPropertyStore(PropertiesService.getScriptProperties())

      // Set the scope. This must match one of the scopes configured during the
      // setup of domain-wide delegation.
      .setScope('https://www.googleapis.com/auth/userinfo.email');
}

/**
 * Parse the private key details from a file stored in Google Drive.
 * @param {string} driveFileId The id of the file in drive to parse.
 */
function getPrivateKeyDetailsFromDriveFile(driveFileId) {
  const file = DriveApp.getFileById(driveFileId);
  return JSON.parse(file.getAs('application/json').getDataAsString());
}
